import { Component } from 'react';
import { Button, Card, Checkbox, Form, Input, message } from 'antd';
import './index.scss';
import imgSrc from 'assets/logo.png';
import { loginAPI } from 'api/user';
export default class Login extends Component {
  // 点击登录按钮
  onFinish = async (values) => {
    try {
      console.log(values);
      const res = await loginAPI(values);
      console.log(res);
      // 存储token
      localStorage.setItem('geek-park', res.data.token);
      // 跳转页面
      this.props.history.push('/');
      // 提示用户
      message.success('登录成功!');
    } catch (error) {
      // console.dir只能打印第一个参数
      console.dir(error);
      if (error.response) {
        message.warn(error.response.data.message);
      }
    }
  };
  render() {
    return (
      <div className="login">
        <Card className="login-container">
          {/* logo图片 */}
          <img src={imgSrc} alt="" className="login-logo" />
          {/* 表单 */}
          <Form
            // 关闭表单输入框输入数据时的默认提示数据
            autoComplete="off"
            onFinish={this.onFinish}
            initialValues={{
              mobile: '13811111111',
              code: '246810',
              agree: true,
            }}
          >
            <Form.Item
              name="mobile"
              //校验规则
              rules={[
                { required: true, message: '不能为空' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入11位手机号码' },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="code"
              rules={[
                // 验证码
                { required: true, message: '验证码不能为空' },
                { pattern: /^\d{6}$/, message: '请输入6位验证码' },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item>
              <Form.Item
                name="agree"
                valuePropName="checked"
                rules={[
                  {
                    validator: (_, value) => {
                      if (value === true) {
                        return Promise.resolve();
                      } else {
                        return Promise.reject(new Error('请勾选并阅读'));
                      }
                    },
                  },
                ]}
              >
                <Checkbox>我已阅读并同意[用户协议]和[隐私条款]</Checkbox>
              </Form.Item>
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                block
                htmlType="submit"
                className="login-form-button"
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    );
  }
}
